//
//  NetWorkTools.swift
//  我的微博
//
//  Created by yz on 15/9/7.
//  Copyright © 2015年 yz. All rights reserved.
//

import UIKit
import AFNetworking
class NetWorkTools: AFHTTPSessionManager {
    
    static let sharedTools:NetWorkTools = {
        let baseURL = NSURL(string: "https://api.weibo.com/")!
        let tools = NetWorkTools(baseURL: baseURL)
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript","text/plain") as Set<NSObject>

        return tools
    }()
    
    // MARK: - OAuth授权
    private let clientId = 4096849763
    private let appSecret = "69234009708e6130f8c954dcc53a843f"
    /// 回调地址
    let redirectUri = "http://www.baidu.com"
    
    /// 返回OAuth授权
    func oauthUrl() -> NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    
    /// 加载TOKEN
    func loadAccessToken(code:String,finished:(result:[String:AnyObject]?,error:NSError?)->()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":clientId,
        "client_secret":appSecret,
        "grant_type":"authorization_code",
        "code":code,
        "redirect_uri":redirectUri]
        
        POST(urlString, parameters: params, success: { (_, JSON) -> Void in

            finished(result: JSON as? [String:AnyObject], error: nil)

            }) { (_, error) -> Void in

                finished(result: nil, error: error)

        }
    }
}





